package cn.cnsy123.shorturls.business.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

import cn.cnsy123.shorturls.api.controller.param.SysDeptInfoDeleteParam;
import cn.cnsy123.shorturls.api.controller.param.SysDeptInfoInsertParam;
import cn.cnsy123.shorturls.api.controller.param.SysDeptInfoQueryParam;
import cn.cnsy123.shorturls.api.controller.param.SysDeptInfoUpdateParam;
import cn.cnsy123.shorturls.api.controller.param.SysDeptUserTreeQueryParam;
import cn.cnsy123.shorturls.api.controller.result.DeptInfoQueryResult;
import cn.cnsy123.shorturls.api.controller.result.Select2Result;
import cn.cnsy123.shorturls.api.controller.result.ZTreeSimpleResult;
import cn.cnsy123.shorturls.api.controller.vo.Select2ResultVo;
import cn.cnsy123.shorturls.api.controller.vo.SysDeptQueryResult;
import cn.cnsy123.shorturls.api.controller.vo.SysDeptSaveResult;
import cn.cnsy123.shorturls.api.controller.vo.ZtreeSimpleResultVo;
import cn.cnsy123.shorturls.business.entity.DeptInfoQueryResultDto;
import cn.cnsy123.shorturls.business.entity.SysDeptInfo;
import cn.cnsy123.shorturls.business.entity.SysDeptZtreeInfo;
import cn.cnsy123.shorturls.business.entity.SysUserInfo;
import cn.cnsy123.shorturls.business.exception.BusinessException;
import cn.cnsy123.shorturls.business.localuser.RequestContext;
import cn.cnsy123.shorturls.business.mapper.SysDeptInfoMapper;
import cn.cnsy123.shorturls.business.mapper.SysUserInfoMapper;
import cn.cnsy123.shorturls.business.service.SysDeptInfoService;
import cn.cnsy123.shorturls.business.util.DateUtil;
import cn.cnsy123.shorturls.business.util.StringUtil;
@Service
public class SysDeptInfoServiceImpl implements SysDeptInfoService {
    
    @Autowired
    private SysDeptInfoMapper sysDeptInfoMapper;
    @Autowired
    private SysUserInfoMapper sysUserInfoMapper;

    @Override
    @Transactional(readOnly=true,propagation = Propagation.REQUIRED,rollbackFor = BusinessException.class)
    public SysDeptQueryResult querySysDeptList(SysDeptInfoQueryParam sysDeptInfoQueryParam) {
        SysDeptQueryResult sysDeptQueryResult = new SysDeptQueryResult();
        try {
            Integer pageNumber = Integer.valueOf((sysDeptInfoQueryParam.getPageNumber().intValue() - 1) * sysDeptInfoQueryParam.getPageSize().intValue());
            List<DeptInfoQueryResultDto> queryResultDtos = sysDeptInfoMapper.selectListByDeptNameAndDeptLeader(sysDeptInfoQueryParam.getDeptName(),sysDeptInfoQueryParam.getDeptLeaderName(),pageNumber,sysDeptInfoQueryParam.getPageSize());
            sysDeptQueryResult.setCode(200);
            String msg = "暂无部门信息数据";
            if(!CollectionUtils.isEmpty(queryResultDtos)) {
                msg = "查询部门信息数据成功";
                sysDeptQueryResult.setData(convertQueryResult(queryResultDtos));
            }
            sysDeptQueryResult.setMsg(msg);
        } catch (Exception e) {
            throw new BusinessException(e);
        }
        
        return sysDeptQueryResult;
    }

    

    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = BusinessException.class)
    public SysDeptSaveResult saveSysDeptInfo(SysDeptInfoInsertParam sysDeptInfoInsertParam) {
        try {
            Integer deptSeq = Integer.valueOf(1);
            Integer parentId = Integer.valueOf(0);
            String realName = RequestContext.get().getRealName();
            boolean updateFlag = true;
            SysDeptInfo record = sysDeptInfoMapper.selectByPrimaryKey(sysDeptInfoInsertParam.getDeptId());
            if(record == null) {
                record = new SysDeptInfo(); 
                updateFlag = false;
            }
            Date nowDate = new Date(System.currentTimeMillis());
            record.setDeptName(sysDeptInfoInsertParam.getDeptName());
            if(sysDeptInfoInsertParam.getParentDept() != null) {
                record.setParentId(sysDeptInfoInsertParam.getParentDept());
                SysDeptInfo lastSysDeptInfo = sysDeptInfoMapper.selectLastByParentId(sysDeptInfoInsertParam.getParentDept());
                if(lastSysDeptInfo != null) {
                    deptSeq = Integer.valueOf(lastSysDeptInfo.getDeptSeq().intValue() + 1);
                }
            }
            if(sysDeptInfoInsertParam.getLeaderId() != null) {
                record.setDeptLeader(sysDeptInfoInsertParam.getLeaderId());
            }
            int flag = -1;
            if(updateFlag) {
                record.setUpdateUser(realName);
                record.setUpdateTime(nowDate);
                record.setRemark("时间:["+DateUtil.getNowTime()+"]更新部门信息,部门名称:["+record.getDeptName()+"],上级部门:["+record.getParentId()+"],部门领导者:["+record.getDeptLeader()+"]");
                flag = sysDeptInfoMapper.updateByPrimaryKeySelective(record);
            }else {
                record.setDeptSeq(deptSeq);
                record.setCreateUser(realName);
                record.setCreateTime(nowDate);
                if(record.getParentId() == null) {
                    record.setParentId(parentId);
                }
                record.setRemark("时间:["+DateUtil.getNowTime()+"]添加部门信息,部门名称:["+record.getDeptName()+"],上级部门:["+record.getParentId()+"],部门领导者:["+record.getDeptLeader()+"]");
                flag = sysDeptInfoMapper.insertSelective(record);
            }
            return flag > 0 ? new SysDeptSaveResult(200, "保存部门信息成功") : new SysDeptSaveResult(100, "保存部门信息失败");
        } catch (Exception e) {
            throw new BusinessException(e);
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = BusinessException.class)
    public SysDeptSaveResult updateSysDeptItem(SysDeptInfoUpdateParam sysDeptInfoUpdateParam) {
        try {
            SysDeptInfo record = new SysDeptInfo();
            record.setId(sysDeptInfoUpdateParam.getDeptId());
            record.setDeptName(sysDeptInfoUpdateParam.getDeptName());
            record.setDeptLeader(sysDeptInfoUpdateParam.getDeptLeaderId());
            record.setParentId(sysDeptInfoUpdateParam.getParentDept());
            int flag = sysDeptInfoMapper.updateByPrimaryKeySelective(record);
            return flag > 0 ? new SysDeptSaveResult(200, "更新部门信息成功") : new SysDeptSaveResult(100, "更新部门信息失败");
        } catch (Exception e) {
            throw new BusinessException(e);
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = BusinessException.class)
    public SysDeptSaveResult deleteSysDeptItem(SysDeptInfoDeleteParam sysDeptInfoDeleteParam) {
        SysDeptSaveResult saveResult = null;
        try {
            SysDeptInfo sysDeptInfo = sysDeptInfoMapper.selectByPrimaryKey(sysDeptInfoDeleteParam.getDeptId());
            if(sysDeptInfo != null) {
                List<SysUserInfo> sysUseByDeptId = sysUserInfoMapper.selectListByDeptId(sysDeptInfoDeleteParam.getDeptId());
                String childrenDeptIdItem = sysDeptInfoMapper.selectChildrenDeptByParentId(sysDeptInfoDeleteParam.getDeptId());
                if(!CollectionUtils.isEmpty(sysUseByDeptId) || StringUtils.isNotBlank(childrenDeptIdItem)) {
                    StringBuffer errorRemarkMsg = new StringBuffer("该部门下还有");
                    if(!CollectionUtils.isEmpty(sysUseByDeptId)) {
                        errorRemarkMsg.append("【").append(sysUseByDeptId.size()).append("】人，");
                    }
                    if(StringUtils.isNotBlank(childrenDeptIdItem)) {
                        errorRemarkMsg.append("【").append(StringUtils.split(childrenDeptIdItem, ",").length).append("】个子部门，");
                    }
                    errorRemarkMsg.append("请先安排人员、子部门调配到其他部门下，谢谢配合！");
                    saveResult = new SysDeptSaveResult(100, errorRemarkMsg.toString());
                }else {
                    int flag = sysDeptInfoMapper.deleteByPrimaryKey(sysDeptInfoDeleteParam.getDeptId());
                    saveResult = (flag > 0) ? new SysDeptSaveResult(200, "删除部门信息成功") : new SysDeptSaveResult(100, "删除部门信息失败，请联系【系统管理员】查询问题！");
                }
            }else {
                saveResult = new SysDeptSaveResult(100,"部门已经不存在了，请【系统管理员】核查相关情况！");
            }
            return saveResult;
        } catch (Exception e) {
            throw new BusinessException(e);
        }
    }

    private List<DeptInfoQueryResult> convertQueryResult(List<DeptInfoQueryResultDto> queryResultDtos) {
        return JSON.parseArray(JSON.toJSONStringWithDateFormat(queryResultDtos, "yyyy-MM-dd HH:mm:ss",SerializerFeature.WriteDateUseDateFormat,SerializerFeature.WriteMapNullValue), DeptInfoQueryResult.class);
    }



    @Override
    @Transactional(readOnly = true,propagation = Propagation.REQUIRED,rollbackFor = BusinessException.class)
    public ZtreeSimpleResultVo querySysDeptTree() {
        try {
            ZtreeSimpleResultVo ztreeSimpleResultVo = new ZtreeSimpleResultVo(100,"查询列表失败");
            List<SysDeptZtreeInfo> ztree = sysDeptInfoMapper.selectListByZtree();
            if(!CollectionUtils.isEmpty(ztree)) {
                ztreeSimpleResultVo.setCode(200);
                ztreeSimpleResultVo.setMsg("查询成功");
                ztreeSimpleResultVo.setTreeData(convertDbToView(ztree));
            }
            
            return ztreeSimpleResultVo;
        } catch (Exception e) {
            throw new BusinessException(e);
        }
    }



    private List<ZTreeSimpleResult> convertDbToView(List<SysDeptZtreeInfo> ztree) {
        List<ZTreeSimpleResult> zTreeSimpleResults = new ArrayList<ZTreeSimpleResult>();
        Iterator<SysDeptZtreeInfo> iterator = ztree.iterator();
        while(iterator.hasNext()) {
            SysDeptZtreeInfo sysDeptZtreeInfo = iterator.next();
            ZTreeSimpleResult zTreeSimpleResult = new ZTreeSimpleResult(sysDeptZtreeInfo.getId(),sysDeptZtreeInfo.getPid(),sysDeptZtreeInfo.getDeptName());
            zTreeSimpleResult.setRealName(StringUtil.convertNotNull(sysDeptZtreeInfo.getRealName()));
            zTreeSimpleResult.setUserPhone(StringUtil.convertNotNull(sysDeptZtreeInfo.getUserPhone()));
            zTreeSimpleResult.setUserTelPhone(StringUtil.convertNotNull(sysDeptZtreeInfo.getUserTel()));
            zTreeSimpleResult.setLeaderUserId(StringUtil.longConvertStr(sysDeptZtreeInfo.getLeaderUserId()));
            zTreeSimpleResults.add(zTreeSimpleResult);
        }
        return zTreeSimpleResults;
    }



    @Override
    @Transactional(readOnly = true,propagation = Propagation.REQUIRED,rollbackFor = BusinessException.class)
    public Select2ResultVo querySysDeptLeaderTree(SysDeptUserTreeQueryParam sysDeptUserTreeQueryParam) {
        try {
            Select2ResultVo select2ResultVo = new Select2ResultVo(200,"获取部门人员信息失败");
            List<SysUserInfo> sysUserInfos = sysUserInfoMapper.selectListByDeptId(sysDeptUserTreeQueryParam.getDeptId());
            if(!CollectionUtils.isEmpty(sysUserInfos)) {
                select2ResultVo.setCode(200);
                select2ResultVo.setMsg("获取部门人员信息成功");
                List<Select2Result> results = new ArrayList<Select2Result>();
                for(SysUserInfo sysUserInfo:sysUserInfos) {
                    results.add(new Select2Result(sysUserInfo.getId(), sysUserInfo.getRealName()));
                }
                select2ResultVo.setSelectData(results);
            }
            List<Select2Result> results = new ArrayList<Select2Result>();
            results.add(new Select2Result(12411L, "超级管理员"));
            return select2ResultVo;
        } catch (Exception e) {
            throw new BusinessException(e);
        }
    }
}
